package com.wlyuan.open.domain.source.service.impl;

import com.alibaba.fastjson.JSON;
import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.open.domain.source.assembler.CombineAssembler;
import com.wlyuan.open.domain.source.assembler.TransportAssembler;
import com.wlyuan.open.domain.source.service.IOpenTransportService;
import com.wlyuan.open.dto.OpenCombineSyncDTO;
import com.wlyuan.open.dto.OpenTransportSyncDTO;
import com.wlyuan.open.dto.transport.OpenTransportRelationSyncDTO;
import com.wlyuan.open.infrastructure.exception.SourceValueErrorException;
import com.wlyuan.transport.rewrite.api.ICombineRewriteService;
import com.wlyuan.transport.rewrite.api.IWaybillRewriteService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;

/**
 * @author yuanzheng
 */
@Service
@Slf4j
@RequiredArgsConstructor
@Data
public class OpenTransportServiceImpl implements IOpenTransportService {
    @DubboReference(check = false)
    private final IWaybillRewriteService waybillRewriteService;
    @DubboReference(check = false)
    private final ICombineRewriteService combineRewriteService;

    @Override
    public Long sync(OpenTransportSyncDTO source) {
        if (CollectionUtils.isEmpty(source.getGoodsList())) {
            source.setGoodsList(Collections.emptyList());
        }
        var creation = TransportAssembler.assemble(source);
        logger.info("同步运单参数：{},{}", source.getSourceKey(), JSON.toJSON(creation));
        var transport = waybillRewriteService.rewriteCheck(creation);
        AssertUtils.assertNotNull(transport, new SourceValueErrorException("创建运单失败"), source);
        return transport.getWaybillId();
    }

    @Override
    public Long sync(OpenCombineSyncDTO source) {
        if (CollectionUtils.isEmpty(source.getTransportIds())) {
            throw new SourceValueErrorException("合单子单不能为空");
        }
        if (CollectionUtils.isEmpty(source.getTransports())) {
            source.setTransports(Collections.emptyList());
        }
        var creation = CombineAssembler.assemble(source);
        logger.info("同步合单参数：{},{}", source.getSourceKey(), JSON.toJSON(creation));
        var combine = combineRewriteService.rewrite(creation);
        AssertUtils.assertNotNull(combine, new SourceValueErrorException("创建合单失败"), source);
        return combine.getCombineId();
    }

    @Override
    public Long sync(OpenTransportRelationSyncDTO source) {
        var creation = TransportAssembler.assemble(source);
        logger.info("同步运单关系参数：{},{}", source.getSourceKey(), JSON.toJSON(creation));
        waybillRewriteService.rewriteRelation(creation);

        return null;
    }
}
